<template>
  <div class="app-container">
    <el-form :inline="true" ref="queryRef" label-position="right" :model="params" label-width="200px" :rules="rules">
      <div class="form-inline">
        <el-row justify="center">
          <el-col :span="11">
            <el-form-item label="项目名称：" class="form-item" prop="projectName">
              <el-input v-model="params.projectName" placeholder="" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="所在行政区（乡镇级别）：" class="form-item" prop="administrativeRegion">
              <el-cascader :props="xzqProps" placeholder="请选择" v-model="params.administrativeRegion" clearable @change="xzqChange"
                ref="checkedAreaRef" class="form-select" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="center">
          <!-- <el-col :span="11">
            <el-form-item label="项目位置：" class="form-location">
              <el-form-item label="经度" label-width="40px" prop="longitude">
                <el-input v-model="params.longitude" placeholder="" class="el-form-longitude" clearable />
              </el-form-item>&emsp;
              <el-form-item label="纬度" label-width="40px" prop="latitude">
                <el-input v-model="params.latitude" placeholder="" class="el-form-latitude" clearable />
              </el-form-item>
            </el-form-item>
          </el-col> -->
          <el-col :span="11">
            <el-form-item label="项目位置：" class="form-location">
              <el-form-item label="经度" label-width="40px">
                <el-form-item label-width="0px" prop="longitude">
                  <el-input v-model="params.longitude" placeholder="" class="el-form-longitude" clearable />
                </el-form-item>
                <span class="line" style="padding:0 3px;">--</span>
                <el-form-item label-width="0px" prop="endLongitude">
                  <el-input v-model="params.endLongitude" placeholder="" class="el-form-longitude" clearable />
                </el-form-item>
              </el-form-item>
              &emsp;
              <el-form-item label="纬度" label-width="40px">
                <el-form-item label-width="0px" prop="latitude">
                  <el-input v-model="params.latitude" placeholder="" class="el-form-longitude" clearable />
                </el-form-item>
                <span class="line" style="padding:0 3px;">--</span>
                <el-form-item label-width="0px" prop="endLatitude">
                  <el-input v-model="params.endLatitude" placeholder="" class="el-form-longitude" clearable />
                </el-form-item>
              </el-form-item>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="报告提交日期：" class="form-item">
              <el-date-picker v-model="params.subTime" type="monthrange" value-format="YYYY-MM" range-separator="至"
                start-placeholder="开始月份" end-placeholder="结束月份">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="center">
          <el-col :span="11">
            <el-form-item label="评审单位：" class="form-item" prop="reviewUnit">
              <el-input v-model="params.reviewUnit" placeholder="" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="承担单位：" class="form-item" prop="undertaker">
              <el-input v-model="params.undertaker" placeholder="" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="center">
          <el-col :span="11">
            <el-form-item label="安评等级：" class="form-item" prop="safetyRating">
              <el-select v-model="params.safetyRating" placeholder="请选择" class="form-select" clearable>
                <el-option v-for="item in safetyRatingOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="登记人：" class="form-item" prop="registrant">
              <el-input v-model="params.registrant" placeholder="" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="center">
          <el-col :span="11">
            <el-form-item label="录入时间：" class="form-item">
              <el-col :span="11">
                <el-date-picker v-model="params.createStartTime" value-format="YYYY-MM-DD" type="date"
                  placeholder="" :size="size" class="form-date" style="width: 130px" />
              </el-col>
              <el-col :span="2">
                <span class="text-gray-500">至</span>
              </el-col>
              <el-col :span="11">
                <el-date-picker v-model="params.createEndTime" value-format="YYYY-MM-DD" type="date"
                  placeholder="" :size="size" class="form-date" style="width: 130px" />
              </el-col>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="所属单位：" class="form-item" prop="registrationUnit">
              <el-input v-model="params.registrationUnit" placeholder="" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="center">
          <el-col :span="11">
            <el-form-item label="状态：" class="form-item" prop="status">
              <el-select placeholder="请选择" class="form-select" v-model="params.status" clearable>
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="审批状态：" class="form-item">
              <el-select placeholder="请选择" class="form-select" v-model="params.approvalStatus" clearable>
                <el-option v-for="item in approveStatusOptions" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="end">
          <el-form-item class="bottom-button">
            <!-- <el-button type="primary" @click="onImport">导入</el-button> -->
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="primary" @click="onRest">重置</el-button>
            <el-button type="primary" @click="onExport">导出</el-button>
            <!-- <el-button type="primary">修改</el-button>
                      <el-button type="primary">删除</el-button>
                      <el-button type="primary">历史操作记录</el-button> -->
          </el-form-item>
        </el-row>
      </div>
    </el-form>

    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="列表展示" name="first">
        <div class="table-wrapper">
          <el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
            @selection-change="handleSelectionChange" :cell-style="{ border: '1px solid #e5ebf7' }"
            :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
            <el-table-column type="selection" width="55" label="序号" />
            <el-table-column prop="projectName" header-align="center" align="center" label="项目名称" width="290">
              <template #default="scope">
                <el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">
                  {{ scope.row.projectName }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="项目位置（中心位置）" header-align="center" align="center">
              <el-table-column prop="longitude" label="经度" header-align="center" align="center" width="110" />
              <el-table-column prop="latitude" label="纬度" header-align="center" align="center" width="110" />
            </el-table-column>
            <el-table-column prop="administrativeRegion" header-align="center" align="center" label="所在行政区（乡镇级别）" />
            <el-table-column label="报告提交日期（到月）">
              <template #default="scope">{{ scope.row.subDate }}</template>
            </el-table-column>
            <el-table-column prop="reviewUnit" header-align="center" align="center" label="评审单位" />
            <el-table-column prop="undertaker" header-align="center" align="center" label="承担单位" />
            <el-table-column prop="safetyRating" header-align="center" align="center" label="安评等级">
              <template #default="scope">
                <span v-if="scope.row.safetyRating=='1'" >Ⅰ</span>
                <span v-else-if="scope.row.safetyRating=='2'" >Ⅱ</span>
                <span v-else-if="scope.row.safetyRating=='3'" >Ⅲ</span>
                <span v-else-if="scope.row.safetyRating=='4'" >Ⅳ</span>
                <span v-else="scope.row.safetyRating=='2+3'" >Ⅱ+Ⅲ</span>
              </template>
            </el-table-column>
            <el-table-column prop="registrant" header-align="center" align="center" label="登记人" />
            <el-table-column prop="createTime" header-align="center" align="center" label="录入时间" />
            <el-table-column prop="registrationUnit" header-align="center" align="center" label="所属单位" />
            <el-table-column prop="status" align="center" label="状态">
              <template #default="scope">
                {{ praseStatus(scope.row.status) }}
              </template>
            </el-table-column>
            <el-table-column prop="approvalStatus" align="center" label="审批状态">
              <template #default="scope">
                {{ approvalStatus(scope.row.approvalStatus) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="scope">
                <el-button type="text" size="small" @click="onApproval(scope.row)" :disabled="scope.row.approvalStatus!='1'&&(m_IsAdministrator||m_userName==scope.row.registrant)" v-if="m_IsAdministrator">审批</el-button>
                <el-button type="text" size="small" @click="onDelete(scope.row)" :disabled="scope.row.approvalStatus=='2'">删除</el-button>
                <el-button type="text" size="small" @click="onModify(scope.row)" :disabled="scope.row.approvalStatus=='2'">修改</el-button>
                <el-button type="text" size="small" @click="onHistoryRecord(scope.row)">历史操作记录</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="paging">
            <el-pagination background v-model:current-page="queryPagination.pageNo" :layout="layout"
              :page-size="queryPagination.pageSize" :total="queryPagination.total" @current-change="handleCurrentChange"
              @size-change="handleSizeChange" />
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="区域位置" name="second">
        <!--地图-->
        <SaResultQueryMap v-show="activeName == 'second'" :dataList="mapDataList" ref="mapRefAPXM"
          @getSaResultsProjectByGeomText="getSaResultsProjectByGeomText" @mapLoading="mapLoading"
          @showDetailResult="showDetailResult"></SaResultQueryMap>
        <!--下方查看详情面板-->
        <div v-if="detailTableBool" class="new-queryResultDiv">
          <div class="new-queryTableBtn">
            <el-button @click="closeDetailResultDiv" type="primary">关闭</el-button>
            <span class="new-queryTableSpan">安评成果项目信息</span>
          </div>
          <div class="new-queryTableDiv">
            <!--安评成果项目信息-->
            <el-table class="listTable" border :data="detailTableData" style="width: 100%"
              :cell-style="{ border: '1px solid #e5ebf7' }"
              :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
              <el-table-column type="selection" width="55" label="序号" />
              <el-table-column prop="projectName" header-align="center" align="center" label="项目名称" width="290">
                <template #default="scope">
                  <el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">
                    {{ scope.row.projectName }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="项目位置（中心位置）" header-align="center" align="center">
                <el-table-column prop="longitude" label="经度" header-align="center" align="center" width="110" />
                <el-table-column prop="latitude" label="纬度" header-align="center" align="center" width="110" />
              </el-table-column>
              <el-table-column prop="administrativeRegion" header-align="center" align="center" label="所在行政区（乡镇级别）" />
              <el-table-column label="报告提交日期（到月）">
                <template #default="scope">{{ scope.row.subDate }}</template>
              </el-table-column>
              <el-table-column prop="reviewUnit" header-align="center" align="center" label="评审单位" />
              <el-table-column prop="undertaker" header-align="center" align="center" label="承担单位" />
              <el-table-column prop="safetyRating" header-align="center" align="center" label="安评等级">
                <template #default="scope">
                  <span v-if="scope.row.safetyRating=='1'" >Ⅰ</span>
                  <span v-else-if="scope.row.safetyRating=='2'" >Ⅱ</span>
                  <span v-else-if="scope.row.safetyRating=='3'" >Ⅲ</span>
                  <span v-else-if="scope.row.safetyRating=='4'" >Ⅳ</span>
                  <span v-else="scope.row.safetyRating=='2+3'" >Ⅱ+Ⅲ</span>
                </template>
              </el-table-column>
              <el-table-column prop="registrant" header-align="center" align="center" label="登记人" />
              <el-table-column prop="createTime" header-align="center" align="center" label="录入时间" />
              <el-table-column prop="registrationUnit" header-align="center" align="center" label="所属单位" />
              <el-table-column prop="status" align="center" label="状态">
                <template #default="scope">
                  {{ praseStatus(scope.row.status) }}
                </template>
              </el-table-column>
              <el-table-column prop="approvalStatus" align="center" label="审批状态">
                <template #default="scope">
                  {{ approvalStatus(scope.row.approvalStatus) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180" fixed="right">
                <template #default="scope">
                  <el-button type="text" size="small" @click="onApproval(scope.row)" :disabled="scope.row.approvalStatus!='1'&&(m_IsAdministrator||m_userName==scope.row.registrant)" v-if="m_IsAdministrator">审批</el-button>
                  <el-button type="text" size="small" @click="onDelete(scope.row)">删除</el-button>
                  <el-button type="text" size="small" @click="onModify(scope.row)">修改</el-button>
                  <el-button type="text" size="small" @click="onHistoryRecord(scope.row)">历史操作记录</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <el-dialog v-model="dialogVisible" title="历史操作记录" width="30%">
      <div class="historyInfo" v-html="historyRecordContent"></div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 审批弹框 -->
    <el-dialog v-model="dialogVisibleSp" title="审批" width="30%">
      <div class="historyInfo" v-html="historyRecordContent"></div>
      <el-form ref="reviewCommentsRef" :model="form" :rules="rules" label-width="120px">
        <p></p>
          <el-form-item label="审批结果" prop="approvalStatus">
            <el-select v-model="form.approvalStatus" placeholder="请选择" style="width: 240px">
              <el-option v-for="item in [{label:'审批通过',value:'2'},{label:'审批不通过',value:'3'}]" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="审核意见" prop="reviewComments">
            <el-input v-model="form.reviewComments" type="textarea" maxlength="500" show-word-limit
              :autosize="{ minRows: 5, maxRows: 5}" placeholder="请输入审核意见" />
          </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleSp = false">取消</el-button>
          <el-button type="primary" @click="submitReviewComments">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改/删除弹框 -->
    <el-dialog v-model="dialogVisibleUpdate" :title="reasonTitle" width="30%">
      <p></p>
      <el-form ref="updateRef" :model="form1" :rules="rules" label-width="120px">
        <p></p>
          <el-form-item :label="reasonTitle=='修改原由'?'修改原由':'删除原由'" prop="reason">
            <el-input v-model="form1.reason" type="textarea" maxlength="500" show-word-limit
              :autosize="{ minRows: 5, maxRows: 5}" placeholder="请输入" />
          </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisibleUpdate = false">取消</el-button>
          <el-button type="primary" @click="submitUpdate">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
//地图
import SaResultQueryMap from '@/map/safetyEvaResCatManagement/project/map.vue';
import { reactive, toRefs, ref, onMounted, getCurrentInstance } from "vue";
import { downloadGet } from '@/utils/request'
import { ElMessage } from 'element-plus'
import {
  safetyRatingList, xzqList, getSaResultsProject, queryHistory,
  querySaResultsProjectByGeomText, queryUserRole, reviewComment, reasonUpdate, reasonDelete
} from "@/api/safetyEvalutionResultsBank/safetyEvaResCatRegister.js";
// 引入接口
import { getInfo } from '@/api/login'
import { getUserId } from "@/utils/auth";
const router = useRouter();

const { proxy } = getCurrentInstance()

// 纬度的数值范围应该在（0，90）即北纬，经度范围在（0，180）即东经，输入的经纬度应该加一个数值校验吧

// 验证经度
const validateLon = (rule, value, callback) => {
  // let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})$/  // 两位小数
  // let reg2 = /^[+]{0,1}(\d+)$/g; // 整数
  let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g; // 整数或小数
  // 如果是必须输入时，取消下面注释
  // if (!value) {
  //   callback(new Error('不能为空'))
  // } else 
  if (!value) {
    callback()
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确数值'))
  } else if (value > 180) {
    callback(new Error('经度必须小于180'))
  } else if (value < 0) {
    callback(new Error('经度必须大于0'))
  } else if (value.indexOf(".") != -1 && value.split(".")[1].length > 6) {
    callback(new Error('最多保留六位小数'));
  } else {
    callback();
  }
};


// 验证纬度
const validateLat = (rule, value, callback) => {
  // let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{0,2})$/  // 两位小数
  // let reg2 = /^[+]{0,1}(\d+)$/g; // 整数
  let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g; // 整数或小数
  // 如果是必须输入时，取消下面注释
  // if (!value) {
  //   callback(new Error('不能为空'))
  // } else 
  if (!value) {
    callback()
  } else if (!reg.test(value)) {
    callback(new Error('请输入正确数值'))
    //this.$set(this.ruleForm, "price", '');
  } else if (value > 90) {
    callback(new Error('纬度必须小于90'))
  } else if (value < 0) {
    callback(new Error('纬度必须大于0'))
  } else if (value.indexOf(".") != -1 && value.split(".")[1].length > 6) {
    callback(new Error('最多保留六位小数'));
  } else {
    callback();
  }
};
const size = ref("");
const dialogVisible = ref(false)
const historyRecordContent = ref('')
const data = reactive({
  // 表单参数
  params: {
    projectName: "", //项目名称
    administrativeRegion: "", //所在行政区
    longitude: "", //项目经度
    latitude: "", //项目纬度
    endLongitude: "",//结束经度
    endLatitude: "",//结束纬度
    reviewUnit: "", //评审单位
    undertaker: "", //承担单位
    safetyRating: "", //安评等级
    registrant: "", //登记人
    createStartTime: "", //录入时间,开始
    createEndTime: "",//录入时间，结束
    registrationUnit: "", //所属单位
    status: "", //状态
    approvalStatus: '',//审批状态,
    subTime: [],
  },
  rules: {
    projectName: [
      { message: "请输入项目名称", trigger: "blur" },
      { max: 50, message: "最多输入50个字", trigger: ["change", "blur"] },
    ],

    longitude: [
      { message: "请输入经度", trigger: "blur" },
      {
        validator: validateLon,
        trigger: ["change", "blur"],
      },
    ],
    endLongitude:[
      { message: "请输入经度", trigger: "blur" },
      {
        validator: validateLon,
        trigger: ["change", "blur"],
      },
    ],
    latitude: [
      { message: "请输入纬度", trigger: "blur" },
      {
        validator: validateLat,
        trigger: ["change", "blur"],
      },
    ],
    endLatitude: [
      { message: "请输入纬度", trigger: "blur" },
      {
        validator: validateLat,
        trigger: ["change", "blur"],
      },
    ],
    reviewUnit: [
      { message: "请输入评审单位", trigger: "blur" },
      { max: 100, message: "最多输入100个字", trigger: ["change", "blur"] },
    ],

    undertaker: [
      { message: "请输入承担单位", trigger: "blur" },
      { max: 100, message: "最多输入100个字", trigger: ["change", "blur"] },
    ],
    approvalStatus: [
      { required:true, message: "请输入审批结果", trigger: "change" },
    ],
    reviewComments: [
      { required:true, message: "请输入审核意见", trigger: "blur" },
    ],
    reason: [
      { required:true, message: "请输入", trigger: "blur" },
    ],
  },
  //分页
  layout: " prev, pager, next, jumper, sizes, total",
  queryPagination: {
    pageNo: 1,
    pageSize: 10,
    total: 0,
  },
  //状态选项
  statusOptions: [
    {
      value: "0",
      label: "无",
    },
    {
      value: "1",
      label: "待修改",
    },
    {
      value: "2",
      label: "已修改",
    },
    {
      value: "3",
      label: "待删除",
    },
    {
      value: "4",
      label: "已删除",
    },
  ],
  //审批状态选项
  approveStatusOptions: [
    {
      value: "0",
      label: "无",
    },
    {
      value: "1",
      label: "待审批",
    },
    {
      value: "2",
      label: "审批通过",
    },
    {
      value: "3",
      label: "审批不通过",
    }
  ],
  safetyRatingOptions: [],
  //表格
  tableData: [],
  form:{
    approvalStatus:'',
    reviewComments:'',
  },
});
const {
  params,
  queryPagination,
  layout,
  rules,
  statusOptions,
  approveStatusOptions,
  safetyRatingOptions,
  tableData,
  form
} = toRefs(data);
const activeName = ref("first");

const handleSizeChange = (val) => {
  onSearch()
};
const handleCurrentChange = (val) => {
  onSearch()
};
const multipleTableRef = ref();
const multipleSelection = ref([]);
const curTableRow = ref(null);
//行政区
const checkedAreaRef = ref();
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  curTableRow.value = val;
};

const onRest = () => {
  proxy.resetForm("queryRef")
  params.value.createStartTime = ''
  queryPagination.value.pageNo = 1
  params.value.createEndTime = ''
  params.value.subTime = []
  params.value.endLongitude = ''
  params.value.endLatitude = ''
  params.value.approvalStatus = ''
  proxy.$refs['mapRefAPXM'].clearAPXMMapQX();
  currentGemo.value=null;
  lastSearchParams.value=null;
  // 清空表格多选状态
  multipleTableRef.value?.clearSelection();
  onSearch();
};

// 查看跳转登记页面
const viewProject = (row) => {
  router.push({ path: '/safetyEvalutionResultsBank/registerView/' + row.projectId })
}

//张平修改
const isRefesh = ref(true);
const handleClick = (tab, event) => {
  // 清空表格多选状态
  multipleTableRef.value?.clearSelection();
  if(activeName.value=="second"&&isRefesh.value) {
    isRefesh.value=false;
    proxy.$refs['mapRefAPXM'].switchTabAPXMMap();
  }else{
    queryPagination.value.pageNo = 1
  }
  onSearch();
}

const lastSearchParams=ref({});
const currentGemo=ref();

const getListAndMapData = ()=>{
  if(activeName.value=="second"){
  const queryMap = {
    ...lastSearchParams.value,
    administrativeRegion: params.value.administrativeRegion.length>0?params.value.administrativeRegion.join(','):'',
    geomText: currentGemo.value,
  }
  //安评成果目录项目信息地图圈选查询
  querySaResultsProjectByGeomText(queryMap).then((res) => {
    if (res.code === 200) {
      mapDataList.value = res.data.rows;
      if (res.data.rows != null && res.data.rows.length > 0) {
        //detailTableData.value = res.data.rows;//表格数据列表
        //detailTableBool.value = true;//显示下方查看详情面板
        let length = res.data.rows.length;
        // proxy.$modal.msgSuccess("查询到" + length + "条数据.");
      } else {
        //detailTableData.value = [];//表格数据列表
        proxy.$modal.msgWarning('圈选范围无查询结果！');
      }
    }
  }).catch(err => {
    console.log(err);
    proxy.$modal.msgError('查询失败！');
  });
}else{
  const query = {
    ...lastSearchParams.value,
    page: queryPagination.value.pageNo,
    rows: queryPagination.value.pageSize,
    geom:currentGemo.value
  }
  if (params.value.administrativeRegion.length > 0) {
    query.administrativeRegion = params.value.administrativeRegion.join(',')
  }
  if (params.value.subTime.length > 0) {
    query.subStartTime = params.value.subTime[0]
    query.subEndTime = params.value.subTime[1]
  }

  getSaResultsProject(query).then((res) => {
    if (res.code === 200) {
      queryPagination.value.total = res.data.total
      tableData.value = [];
      const rows = res.data.rows;
      //循环遍历之前加上非空判断
      if (rows.length >= 0) {
        rows.forEach((item) => {
          tableData.value.push({
            projectId: item.projectId,
            originalDataId: item.originalDataId,
            projectName: item.projectName,
            longitude: item.longitude,
            latitude: item.latitude,
            administrativeRegion: item.administrativeRegion,
            subDate: item.subDate,
            reviewUnit: item.reviewUnit,
            undertaker: item.undertaker,
            safetyRating: item.safetyRating,
            registrant: item.registrant,
            createTime: item.createTime,
            registrationUnit: item.registrationUnit,
            status: item.status,
            //approveStatus: item.approveStatus,
            approvalStatus: item.approvalStatus,
            logId:item.logId
          });
        });
      }
    }
  }).catch(err => {
            console.log(err);
          }
  );
}
};

//张平修改

//项目信息表格查询
const onSearch = () => {
  lastSearchParams.value=JSON.parse(JSON.stringify(params.value));
  getListAndMapData();
};
const praseStatus = (code) => {
  let codeStr = '无'
  switch (code) {
    case "0":
      codeStr = '无'
      break;
    case "1":
      codeStr = '待修改'
      break;
    case "2":
      codeStr = '已修改'
      break;
    case "3":
      codeStr = '待删除'
      break;
    case "4":
      codeStr = '已删除'
      break;
    default:
      break;
  }
  return codeStr
}
//审批状态选项
const approvalStatus = (code) => {
  let codeStr = '无'
  switch (code) {
    case "0":
      codeStr = '无'
      break;
    case "1":
      codeStr = '待审批'
      break;
    case "2":
      codeStr = '审批通过'
      break;
    case "3":
      codeStr = '审批不通过'
      break;
    default:
      break;
  }
  return codeStr
}

// 审批
const dialogVisibleSp = ref(false);
const reviewCommentId = ref('');
const onApproval = (row)=>{
  reviewCommentId.value = row.projectId;
  dialogVisibleSp.value = true;
  proxy.resetForm("reviewCommentsRef");
  const paramsp = {
    //projectId: row.projectId
    type:'1',
    id: row.logId
  }
  historyRecordContent.value = ""
  queryHistory(paramsp).then(res => {
    if (res.code === 200) {
      res.data.forEach(item => {
        // 审批结果
        let strApprove = '';
        if(item.status == 0) {
          strApprove = '待审批。';
        } else if(item.status == 1) {
          strApprove = '已审批。';
        } else if(item.status == 2) {
          strApprove = '审批未通过。';
        }
        // 修改
        if (item.operation.indexOf('修改') != -1) {
          historyRecordContent.value += `<span>${item.company||''}${item.userName||''}</span>于<span>${item.operationTime||''}</span>${item.operation||''}了<span>${item.tableName||''}${item.field||''}</span>信息，更改前：<span>${item.beforeUpdating||''}</span>，更改后：<span>${item.afterUpdate||''}</span>，${strApprove}<br/>`
        }
        // 删除
        else {
          historyRecordContent.value += `<span>${item.company||''}${item.userName||''}</span>于<span>${item.operationTime||''}</span>${item.operation||''}，${strApprove}<br/>`
        }
      })
    }
  }).catch(err => {
    console.log(err)
  })
}
const submitReviewComments = ()=>{
  proxy.$refs['reviewCommentsRef'].validate((valid, fields) => {
    if (valid) {
      const query = {
        type:'1',
        id:reviewCommentId.value,
        status:form.value.approvalStatus,
        opinion:form.value.reviewComments
      }
      reviewComment(query).then(res=>{
        proxy.$modal.msgSuccess("审批完成");
        onSearch()
        dialogVisibleSp.value = false;
      }).catch(err=>{console.log(err)})
    } else {
      proxy.$refs['reviewCommentsRef'].scrollToField(Object.keys(fields)[0])
    }
  })
} 

//项目信息删除
const onDelete = (row) => {
  reasonTitle.value = '删除原由';
  dialogVisibleUpdate.value = true
  proxy.resetForm("updateRef");
  form1.id = row.projectId;;
  form1.type = '1';
  return;
  router.push({ path: '/safetyEvalutionResultsBank/safetyEvaResCatRegister', query: { operate: 'delete', projectId: row.projectId } })
  // const params = {
  //   reviewComments: row.reviewComments,
  //   approvalStatus: row.approvalStatus,
  //   // projectId: row.projectId
  //   deleteReason:row.deleteReason

  // }
  // ElMessageBox.confirm('此操作将删除数据, 是否继续?', '提示', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消',
  //   type: 'warning'
  // }).then(() => {
  //   deleteSaResultsProject(params).then((res) => {
  //     console.log(res)
  //     if (res.data === '删除成功') {
  //       ElMessage({
  //         type: 'success',
  //         message: '删除成功!'
  //       });
  //       onSearch()
  //     }

  //   }).catch(err => {
  //     console.log(err);
  //     ElMessage({
  //       type: 'error',
  //       message: '删除失败!'
  //     });
  //   })

  // }).catch(() => {
  //   ElMessage({
  //     type: 'info',
  //     message: '已取消删除'
  //   });
  // });

}

//修改
const dialogVisibleUpdate = ref(false);
const reasonTitle = ref('');
const form1 = ref({
  reason:'',
  id:''
})
const onModify = (row) => {
  if(m_IsAdministrator.value&&(m_userName.value!=row.registrant)){
    reasonTitle.value = '修改原由'
    dialogVisibleUpdate.value = true;
    proxy.resetForm("updateRef");
    form1.id = row.projectId;
    form1.type = '1';
    return;
  }
  // const params = {
  //   reviewComments: row.reviewComments,
  //   approvalStatus: row.approvalStatus
  // }
  router.push({ path: '/safetyEvalutionResultsBank/safetyEvaResCatRegister', query: { operate: 'modify', projectId: row.projectId } })
}
const submitUpdate = ()=>{
  proxy.$refs['updateRef'].validate((valid, fields) => {
    if (valid) {
      if(reasonTitle.value=='修改原由'){
        reasonUpdate(form1).then(res=>{
          proxy.$modal.msgSuccess("修改完成");
          onSearch()
          dialogVisibleUpdate.value = false;
        }).catch(err=>{console.log(err)})
      }else{
        reasonDelete(form1).then(res=>{
          proxy.$modal.msgSuccess("删除完成");
          onSearch()
          dialogVisibleUpdate.value = false;
        }).catch(err=>{console.log(err)})
      }
    } else {
      proxy.$refs['updateRef'].scrollToField(Object.keys(fields)[0])
    }
  })  
}

// 历史操作记录
const onHistoryRecord = (row) => {
  dialogVisible.value = true
  const paramsp = {
    //projectId: row.projectId
    type:'2',
    id: row.logId
    // originalDataId: row.originalDataId
  }
  historyRecordContent.value = ""
  queryHistory(paramsp).then(res => {
    if (res.code === 200) {
      res.data.forEach(item => {
        // 审批结果
        let strApprove = '';
        if(item.status == 0) {
          strApprove = '待审批。';
        } else if(item.status == 1) {
          strApprove = '已审批。';
        } else if(item.status == 2) {
          strApprove = '审批未通过。';
        }
        // 修改
        if (item.operation.indexOf('修改') != -1) {
          historyRecordContent.value += `<span>${item.company||''}${item.userName||''}</span>于<span>${item.operationTime||''}</span>${item.operation||''}了<span>${item.tableName||''}${item.field||''}</span>信息，更改前：<span>${item.beforeUpdating||''}</span>，更改后：<span>${item.afterUpdate||''}</span>，${strApprove}<br/>`
        }
        // 删除
        else {
          historyRecordContent.value += `<span>${item.company||''}${item.userName||''}</span>于<span>${item.operationTime||''}</span>${item.operation||''}，${strApprove}<br/>`
        }
      })
    }
  }).catch(err => {
    console.log(err)
  })
}

//导入
const onImport = () => {
  // importExcelSaResults().then((res) => {
  //   console.log(res)

  // }).catch(err => {
  //   console.log(err);
  // })
  router.push({ path: '/safetyEvalutionResultsBank/safetyEvaResCatRegister' })
}
//导出
// const baseURL = import.meta.env.VITE_APP_BASE_API
const onExport = () => {
  if (!curTableRow.value || curTableRow.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据!'
    });
    return
  }
  const params = {
    projectId: curTableRow.value[0].projectId
  }
  // downloadGet('http://10.13.155.119:8081/fxfzdzqh/saResults/exportExcelSaResults', params, '文件.xls')
  downloadGet('/saResults/exportExcelSaResults', params, '安评成果目录项目信息.xls')
}

/** 安评等级列表 */
const getSafetyRatingList = () => {
  safetyRatingList().then((res) => {
    if (res.code === 200) {
      safetyRatingOptions.value = [];
      const options = res.data.sort((a, b) => a.sort - b.sort);
      options.forEach((item) => {
        safetyRatingOptions.value.push({
          value: item.dictItemCode,
          label: item.dictItemName,
        });
      });
    }
  }).catch(err => {
    console.log(err);
  });
};
const xzqChange = (value) => {
  params.value.administrativeRegion = value
}
/** 行政区列表 */
const xzqProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    let { value } = node
    //console.log(node)
    // 没有value,说明是省，赋值1
    if (!value) {
      value = 1
    }
    // 构造参数
    const params = {
      divisionId: value
    }
    xzqList(params).then((res) => {
      //console.log(res)
      if (res.code === 200) {
        const nodes = []
        res.data.forEach(item => {
          nodes.push({
            value: item.value,
            label: item.name,
            leaf: item.isLeaf,
          }
          )
        })
        // Invoke `resolve` callback to return the child nodes data and indicate the loading is finished.
        resolve(nodes)
      }
    })
  },
}

// 判断是否管理员
const m_IsAdministrator = ref(false)
const m_userName = ref('')
// 获取用户角色
const getUserRole = () => {
  queryUserRole().then(res => {
    if (res.code === 200) {
      m_IsAdministrator.value = res.data
    }
  }).catch(error => {
  })
}

// 获取用户
function getUserInfo() {
  getInfo(getUserId()).then(response => {
    m_userName.value = response.user.userName
  });
};

// 挂载
onMounted(() => {
  // 获取用户角色
  getUserRole();
  getUserInfo();
  getSafetyRatingList();
  onSearch()
});

//地图传参--start
const mapDataList = ref([]);//地图圈选查询结果列表
//安评成果目录项目信息地图圈选查询
const getSaResultsProjectByGeomText = (geomText) => {
  if (geomText != null && geomText != "") {
    currentGemo.value=geomText;
    getListAndMapData();

    /*const query = {
      ...params.value,
      geomText: geomText,
    }
    //安评成果目录项目信息地图圈选查询
    querySaResultsProjectByGeomText(query).then((res) => {
      if (res.code === 200) {
        mapDataList.value = res.data.rows;
        if (res.data.rows != null && res.data.rows.length > 0) {
          //detailTableData.value = res.data.rows;//表格数据列表
          //detailTableBool.value = true;//显示下方查看详情面板
          let length = res.data.rows.length;
          proxy.$modal.msgSuccess("查询到" + length + "条数据.");
        } else {
          //detailTableData.value = [];//表格数据列表
          proxy.$modal.msgWarning('圈选范围无查询结果！');
        }
      }
    }).catch(err => {
      console.log(err);
      proxy.$modal.msgError('查询失败！');
    });*/
  }
};
//查询状态
const mapLoading = (bool) => {
  if (bool) {
    proxy.$modal.loading("正在查询，请稍候...");
  } else {
    proxy.$modal.closeLoading();
  }
};
//下方查看详情面板数据
const detailTableData = ref([]);
//是否显示下方查看详情面板
const detailTableBool = ref(false);
//关闭下方查看详情面板
const closeDetailResultDiv = () => {
  detailTableBool.value = false;
}
//查看详情
const showDetailResult = (row) => {
  if (row != null) {
    detailTableData.value = [row];//表格数据列表
    detailTableBool.value = true;//显示下方查看详情面板
  }
}
//地图传参--end
</script>

<style lang="scss" scoped>
:deep(.historyInfo) {
  line-height: 30px;
  span {
    color: red;
  }
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.form-inline {
  :deep(.el-form-item__error) {
    z-index: 1;
  }

  .form-item {
    :deep(.el-form-item__content) {
      width: 300px;
    }

    .form-select {
      width: 300px;
    }

    .form-date {
      width: 130px;
    }
  }

  .form-location {
    .el-form-item {
      margin-right: 0;
    }

    .el-form-longitude,
    .el-form-latitude {
      width: 100px;
    }
  }
}

.paging {
  padding: 20px 10%;
  .el-pagination{
    justify-content: center;
  }
}
</style>